package tech.eyao.hs60x.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;

import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.enums.ExceptionCodeEnum;
import tech.eyao.hs60x.manager.SignManager;

public class AuthenticationFliter extends AbstractFliter implements Ordered {
	private static final Logger	logger	= LoggerFactory.getLogger(AuthenticationFliter.class);
	private static List<String> noUrl = new ArrayList<String>();
	
	@Autowired
	private SignManager			signManager;
	
	
	public String getServletPath(HttpServletRequest request) {
		String servletPath = (String) request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE);
		if (servletPath == null) {
			servletPath = request.getServletPath();
		}
		return servletPath;
	}

	public void filter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		String url = httpServletRequest.getRequestURI();
		logger.info("AuthenticationFliter"+ "' received request for [" + url + "]" + httpServletRequest.getQueryString());
		url = BeanUtils.instantiate(UrlPathHelper.class).getLookupPathForRequest(httpServletRequest);
		if (!noUrl.contains(url)) {
			String token = httpServletRequest.getHeader(CommonConstants.REQUEST_HEADER_TOKE_NNAME);

			if (StringUtils.isEmpty(token)) {
				httpServletResponse.setStatus(HttpStatus.NOT_FOUND.value());
				httpServletResponse.setContentType("application/json");
				new BaseResult();
				httpServletResponse.getWriter().print(JSON.toJSONString(BaseResult.isBussinessFail("非法请求,token不能为空")));
				return;
			}

			// 验证token签名
			if (!signManager.verify(token) || !signManager.checkAccount(token)) {
				httpServletResponse.getWriter().print(JSON.toJSONString(BaseResult.isFailure(ExceptionCodeEnum.TOKEN_EXPIRE.getCode(),
				        ExceptionCodeEnum.TOKEN_EXPIRE.getMessage())));
				return;
			} else {
				chain.doFilter(httpServletRequest, httpServletResponse);
			}
		} else {
			chain.doFilter(httpServletRequest, httpServletResponse);
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {

	}

	@Override
	public int getOrder() {
		return 0;
	}

	/**
	 * 添加过滤URI
	 * @param loginMethod
	 */
	public void setNoNrl(String loginMethod) {
		noUrl.add(loginMethod);
	}
}
